package com.blog.controller.admin;

import com.blog.constant.LogActions;
import com.blog.constant.Types;
import com.blog.constant.WebConst;
import com.blog.controller.BaseController;
import com.blog.dto.cond.ContentCondition;
import com.blog.dto.cond.MetaCondition;
import com.blog.model.Content;
import com.blog.model.Meta;
import com.blog.model.User;
import com.blog.service.content.ContentService;
import com.blog.service.log.LogService;
import com.blog.service.meta.MetaService;
import com.blog.utils.ResultVoUtil;
import com.blog.vo.ResultVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;

/**
 * 文章管理页面
 *
 * @author wmb
 *
 * @since 2021-2-8
 */
@Api("文章管理相关接口")
@Controller
public class ArticleController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ArticleController.class);

    @Autowired
    @Qualifier("contentService")
    private ContentService contentService;

    @Autowired
    @Qualifier("metaService")
    private MetaService metaService;

    @Autowired
    @Qualifier("logService")
    private LogService logService;

    @ApiOperation("文章管理页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", defaultValue = "1", paramType = "query", dataType = "int", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", defaultValue = "15", paramType = "query", dataType = "int", required = false)
    })
    @GetMapping("/admin/article")
    public String articleIndex(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                        @RequestParam(value = "pageSize", defaultValue = "15", required = false) Integer pageSize,
                        @ApiIgnore HttpServletRequest request) {
        PageInfo<Content> articlePageInfo = contentService.getArticlesByCond(new ContentCondition(), pageNum, pageSize);
        request.setAttribute("articles", articlePageInfo);
        return "admin/article_list";
    }

    @ApiOperation("发表文章页")
    @GetMapping("/admin/article/publish")
    public String publishIndex(@ApiIgnore HttpServletRequest request) {
        MetaCondition metaCondition = new MetaCondition();
        metaCondition.setType(Types.CATEGORY.getType());
        List<Meta> metaList = metaService.getMetas(metaCondition);
        request.setAttribute("categories", metaList);
        return "admin/article_edit";
    }

    @ApiOperation("添加新文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "文章标题", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "titlePic", value = "标题图片", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "slug", value = "内容缩略名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "content", value = "文章内容", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "type", value = "文章类型", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "文章状态", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "tags", value = "标签列表", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "categories", value = "分类", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "allowComment", value = "是否被允许被评论", paramType = "query", dataType = "Boolean", required = true)
    })
    @PostMapping("/admin/article/publish")
    @ResponseBody
    public ResultVo saveArticle(@Size(max = 200, message = "文章标题过长") @NotBlank(message = "文章标题不允许为空") @RequestParam("title") String title,
                                @RequestParam(value = "titlePic", defaultValue = "", required = false) String titlePicture,
                                @RequestParam(value = "slug", required = false) String slug,
                                @Size(max = 200000, message = "文章字数超过限制") @NotBlank(message = "文章内容不允许为空") @RequestParam("content") String content,
                                @NotBlank(message = "文章类型不允许为空") @RequestParam("type") String type,
                                @NotBlank(message = "文章状态不允许为空") @RequestParam("status") String status,
                                @RequestParam(value = "tags", defaultValue = "", required = false) String tags,
                                @RequestParam(value = "categories", defaultValue = "", required = false) String categories,
                                @NotNull(message = "是否被允许被评论不能为空") @RequestParam(value = "allowComment") Boolean allowComment,
                                @ApiIgnore HttpSession session) {
        User user = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        Content contentDomain = new Content();
        contentDomain.setTitle(title);
        contentDomain.setTitlePicture(titlePicture);
        contentDomain.setSlug(slug);
        contentDomain.setContent(content);
        contentDomain.setType(type);
        contentDomain.setStatus(status);
        contentDomain.setTags(type.equals(Types.ARTICLE.getType()) ? tags : null);
        // 只允许博客文章有分类，防止作品被收入分类
        contentDomain.setCategories(type.equals(Types.ARTICLE.getType()) ? categories : null);
        contentDomain.setAllowComment(allowComment ? 1 : 0);
        contentDomain.setCreateTime(new Date());
        contentDomain.setAuthorId(user.getUid());

        contentService.addArticle(contentDomain);

        return ResultVoUtil.success();
    }

    @ApiOperation("文章编辑页")
    @GetMapping("/admin/article/{cid}")
    public String editArticle(@NotNull(message = "文章编号不允许为空") @PathVariable("cid") Integer cid,
                              @ApiIgnore HttpServletRequest request) {
        Content content = contentService.getArticleById(cid);
        request.setAttribute("contents", content);
        MetaCondition metaCondition = new MetaCondition();
        metaCondition.setType(Types.CATEGORY.getType());
        List<Meta> metaList = metaService.getMetas(metaCondition);
        request.setAttribute("categories", metaList);
        request.setAttribute("active", "article");
        return "admin/article_edit";
    }

    @ApiOperation("编辑保存文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cid", value = "文章主键", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "title", value = "文章标题", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "titlePic", value = "标题图片", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "slug", value = "内容缩略名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "content", value = "文章内容", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "type", value = "文章类型", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "文章状态", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "tags", value = "标签列表", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "categories", value = "分类", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "allowComment", value = "是否被允许被评论", paramType = "query", dataType = "Boolean", required = true)
    })
    @PostMapping("/admin/article/modify")
    @ResponseBody
    public ResultVo modifyArticle(@NotNull(message = "文章id不允许为空") @RequestParam("cid") Integer cid,
                                @Size(max = 200, message = "文章标题过长") @NotBlank(message = "文章标题不允许为空") @RequestParam("title") String title,
                                @RequestParam(value = "titlePic", defaultValue = "", required = false) String titlePicture,
                                @RequestParam(value = "slug", required = false) String slug,
                                @Size(max = 200000, message = "文章字数超过限制") @NotBlank(message = "文章内容不允许为空") @RequestParam("content") String content,
                                @NotBlank(message = "文章类型不允许为空") @RequestParam("type") String type,
                                @NotBlank(message = "文章状态不允许为空") @RequestParam("status") String status,
                                @RequestParam(value = "tags", defaultValue = "", required = false) String tags,
                                @RequestParam(value = "categories", defaultValue = "", required = false) String categories,
                                @NotNull(message = "是否被允许被评论不能为空") @RequestParam(value = "allowComment") Boolean allowComment,
                                @ApiIgnore HttpSession session) {
        User user = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        Content contentDomain = new Content();
        contentDomain.setId(cid);
        contentDomain.setTitle(title);
        contentDomain.setTitlePicture(titlePicture);
        contentDomain.setSlug(slug);
        contentDomain.setContent(content);
        contentDomain.setType(type);
        contentDomain.setStatus(status);
        contentDomain.setTags(tags);
        // 只允许博客文章有分类，防止作品被收入分类
        contentDomain.setCategories(categories);
        contentDomain.setAllowComment(allowComment ? 1 : 0);
        contentDomain.setAuthorId(user.getUid());
        contentDomain.setCommentsNum(0);

        contentService.updateArticleById(contentDomain);

        return ResultVoUtil.success();
    }

    @ApiOperation("删除文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cid", value = "文章主键id", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping(value = "/admin/article/delete")
    @ResponseBody
    public ResultVo deleteArticle(@NotNull(message = "文章主键不允许为空") @RequestParam("cid") Integer cid,
                                  @ApiIgnore HttpServletRequest request) {
        contentService.deleteArticleById(cid);
        logService.addLog(LogActions.DEL_ARTICLE.getAction(), cid + "", request.getRemoteAddr(), super.getUid(request));
        return ResultVoUtil.success();
    }
}
